<div class="row">
    <!-- 订单基本信息 -->
    <div class="col-xs-12">
        <div class="box box-primary">
            <div class="box-header with-border">
                <h3 class="box-title">订单基本信息</h3>
            </div>
            <div class="box-body">
                <div class="row">
                    <div class="col-md-6">
                        <table class="table table-borderless">
                            <tr>
                                <td width="120" class="text-right"><strong>医院名称：</strong></td>
                                <td>{$order.hospital_name|default='--'}</td>
                            </tr>
                            <tr>
                                <td width="120" class="text-right"><strong>套餐名称：</strong></td>
                                <td>{$order.package_name}</td>
                            </tr>
                            <tr>
                                <td width="120" class="text-right"><strong>体检人：</strong></td>
                                <td>{$order.exam_person_name}</td>
                            </tr>
                            <tr>
                                <td width="120" class="text-right"><strong>联系电话：</strong></td>
                                <td>{$order.exam_person_phone}</td>
                            </tr>
                        </table>
                    </div>
                    <div class="col-md-6">
                        <table class="table table-borderless">
                            <tr>
                                <td width="120" class="text-right"><strong>体检日期：</strong></td>
                                <td>{$order.exam_date}</td>
                            </tr>
                            <tr>
                                <td width="120" class="text-right"><strong>体检时段：</strong></td>
                                <td>{$order.exam_time_slot}</td>
                            </tr>
                            <tr>
                                <td width="120" class="text-right"><strong>订单状态：</strong></td>
                                <td>
                                    {if $order.status == '1'}
                                    <span class="label label-warning">待核销</span>
                                    {elseif $order.status == "2"}
                                    <span class="label label-danger">已取消</span>
                                    {elseif $order.status == "3"}
                                    <span class="label label-info">待上传报告</span>
                                    {elseif $order.status == "4"}
                                    <span class="label label-success">已完成</span>
                                    {/if}
                                </td>
                            </tr>
                            <tr>
                                <td width="120" class="text-right"><strong>订单金额：</strong></td>
                                <td class="text-red">¥{$order.pay_price}</td>
                            </tr>
                        </table>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-12">
                        <table class="table table-borderless">
                            <tr>
                                <td width="120" class="text-right"><strong>备注信息：</strong></td>
                                <td>{$order.remark|default='无'}</td>
                            </tr>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 体检项目明细及报告上传 -->
<div class="row">
    <div class="col-xs-12">
        <div class="box box-success">
            <div class="box-header with-border">
                <h3 class="box-title">体检项目明细（共{$items|count}项）</h3>
            </div>
            <div class="box-body">
                <table class="table table-hover table-striped">
                    <thead>
                        <tr>
                            <th width="50">#</th>
                            <th>项目名称</th>
                            <th>项目价格</th>
                            <th>报告状态</th>
                            <th>上传时间</th>
                            <th width="200">操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        {volist name="items" id="item"}
                        <tr>
                            <td>{$item.id}</td>
                            <td>
                                <strong>{$item.item_name}</strong>
                                <p class="text-muted text-sm mt-1">{$item.item_description|default='无描述'}</p>
                            </td>
                            <td>¥{$item.item_price}</td>
                            <td>
                                {if $item.report_url}
                                <span class="label label-success">
                                    {$item.report_type == 'image' ? '图片报告' : 'PDF报告'}
                                </span>
                                {else}
                                <span class="label label-warning">未上传</span>
                                {/if}
                            </td>
                            <td>{$item.report_time|default='-'}</td>
                            <td>
                                {if $item.report_url}
                                <!-- 已上传报告：查看和删除 -->
                                <a href="javascript:;" class="btn btn-xs btn-info"
                                   onclick="viewReport('{$item.report_url}', '{$item.report_type}')">
                                    查看报告
                                </a>
                                <a href="javascript:;" class="btn btn-xs btn-danger"
                                   onclick="deleteReport({$item.id})">
                                    删除
                                </a>
                                {else}
                                <!-- 未上传报告：上传按钮 -->
                                <button type="button" class="btn btn-xs btn-primary"
                                        data-toggle="modal" data-target="#uploadModal"
                                        onclick="setUploadItem({$item.id})">
                                    上传报告
                                </button>
                                {/if}
                            </td>
                        </tr>
                        {/volist}
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- 上传报告模态框 -->
<div class="modal fade" id="uploadModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">上传项目报告：<span id="currentItemName">未选择项目</span></h4>
            </div>
            <form id="uploadForm" enctype="multipart/form-data">
                <div class="modal-body">
                    <input type="hidden" name="item_id" id="uploadItemId">
                    <div class="form-group">
                        <label for="reportType">报告类型</label>
                        <select class="form-control" id="reportType" name="type">
                            {volist name="mediaTypes" id="type"}
                            <option value="{$type.value}">{$type.text}</option>
                            {/volist}
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="reportFile">选择文件</label>
                        <input type="file" id="reportFile" name="file">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">确认上传</button>
                </div>
            </form>
        </div>
    </div>
</div>

{block name="script"}
<script>
// 1. 全局变量
let currentItemId = 0;

// 2. 设置上传项目ID
function setUploadItem(itemId) {
    currentItemId = itemId;
    const uploadItemIdEl = document.getElementById('uploadItemId');
    if (uploadItemIdEl) uploadItemIdEl.value = itemId;

    // 显示当前项目名称
    const itemNameEl = document.querySelector(`tr:has(button[onclick="setUploadItem(${itemId})"]) strong`);
    const currentItemNameEl = document.getElementById('currentItemName');
    if (itemNameEl && currentItemNameEl) {
        currentItemNameEl.textContent = itemNameEl.textContent || '未知项目';
    }

    console.log("setUploadItem执行成功，项目ID：", itemId);
}

// 3. 查看报告
function viewReport(url, type) {
    if (type === 'image' && window.FastAdmin) {
        Fast.api.open(url, '报告预览', {area: ['80%', '80%'], btn: ['关闭']});
    } else {
        window.open(url);
    }
}

// 4. 删除报告
function deleteReport(itemId) {
    if (window.FastAdmin && Fast.api.confirm) {
        Fast.api.confirm('确定要删除该报告吗？删除后不可恢复', function() {
            sendDeleteRequest(itemId);
        });
    } else {
        if (confirm('确定要删除该报告吗？删除后不可恢复')) {
            sendDeleteRequest(itemId);
        }
    }
}

// 5. 发送删除请求
function sendDeleteRequest(itemId) {
    const xhr = new XMLHttpRequest();
    const deleteUrl = "{:url('deleteReport')}?item_id=" + itemId;
    xhr.open('GET', deleteUrl, true);

    xhr.onload = function() {
        showMsg('删除成功', 'success');
        window.location.reload();
    };

    xhr.onerror = function() {
        showMsg('网络错误，请检查连接后重试', 'error');
    };

    xhr.send();
}

// 6. 消息提示封装
function showMsg(content, type) {
    if (window.Layer) {
        const icon = type === 'success' ? 1 : 2;
        Layer.msg(content, {icon: icon, time: 1500});
    } else {
        alert(content);
    }
}

// 7. 辅助函数：获取文件扩展名
function getFileExtension(file) {
    return file.name.split('.').pop().toLowerCase();
}

// 8. 辅助函数：校验文件类型是否匹配选择的报告类型
function checkFileTypeMatch(reportType, file) {
    const ext = getFileExtension(file);
    if (reportType === 'image') {
        return ['jpg', 'jpeg', 'png', 'gif'].includes(ext);
    } else if (reportType === 'pdf') {
        return ext === 'pdf';
    }
    return false;
}

// 9. 表单提交处理（核心修复部分）
document.addEventListener('DOMContentLoaded', function() {
    const uploadForm = document.getElementById('uploadForm');
    if (!uploadForm) {
        console.log("未找到上传表单，表单提交逻辑未初始化");
        return;
    }

    // 动态更新文件类型提示（含允许格式）
    const reportTypeEl = document.getElementById('reportType');
    const fileTypeTipEl = document.getElementById('fileTypeTip');
    if (reportTypeEl && fileTypeTipEl) {
        reportTypeEl.addEventListener('change', function() {
            const type = this.value;
            const [fileText, allowTypes] = type === 'image'
                ? ['JPG、PNG、GIF图片', '允许格式：.jpg .png .gif']
                : ['PDF文档', '允许格式：.pdf'];

            // 更新帮助文本和允许格式提示
            this.closest('.form-group').querySelector('.help-block').textContent = `支持上传${fileText}，最大10MB`;
            fileTypeTipEl.textContent = allowTypes;
        });
    }

    // 表单提交事件（核心修复）
    uploadForm.addEventListener('submit', function(e) {
        e.preventDefault();
        e.stopPropagation();

        // 1. 基础校验
        const itemId = document.getElementById('uploadItemId').value;
        const reportType = document.getElementById('reportType').value;
        const fileInput = document.getElementById('reportFile');
        const file = fileInput.files[0];

        if (!itemId) {
            showMsg('请选择要上传的体检项目', 'error');
            return;
        }
        if (!file) {
            showMsg('请选择要上传的文件', 'error');
            return;
        }

        // 2. 新增：校验文件大小（≤10MB）
        const maxSize = 10 * 1024 * 1024; // 10MB
        if (file.size > maxSize) {
            showMsg('文件大小超过10MB限制，请选择更小的文件', 'error');
            return;
        }

        // 3. 新增：校验文件类型与报告类型匹配
        if (!checkFileTypeMatch(reportType, file)) {
            const allowTypes = reportType === 'image' ? 'jpg、png、gif' : 'pdf';
            showMsg(`文件类型不匹配！请选择${allowTypes}格式文件`, 'error');
            return;
        }

        // 4. 核心修复：构建FormData时，补全文件元信息（文件名+MIME类型）
        const formData = new FormData(uploadForm);
        const fileName = file.name; // 保留原文件名（含扩展名）
        const fileMimeType = file.type || (reportType === 'image' ? 'image/jpeg' : 'application/pdf'); // 兜底MIME类型

        // 移除原有file字段，重新append（确保元信息完整）
        formData.delete('file');
        formData.append('file', file, fileName); // 第三个参数必传：文件名（含扩展名）
        formData.append('item_id', itemId);
        formData.append('type', reportType);
        formData.append('file_ext', getFileExtension(file)); // 新增：单独传递扩展名，方便服务端校验

        // 5. 上传配置
        const uploadUrl = "{:url('uploadReport')}";
        const submitBtn = uploadForm.querySelector('button[type="submit"]');

        // 上传中状态
        submitBtn.disabled = true;
        submitBtn.textContent = '上传中...';
        let loadIndex = null;
        if (window.Layer) {
            loadIndex = Layer.load(2, {shade: [0.3, '#000']});
        }

        // 6. 原生AJAX上传（保留原有逻辑，仅优化FormData）
        const xhr = new XMLHttpRequest();
        xhr.open('POST', uploadUrl, true);

        // 新增：设置请求头（可选，部分服务端需要）
        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

        xhr.onload = function() {
            submitBtn.disabled = false;
            submitBtn.textContent = '确认上传';
            if (loadIndex !== null && window.Layer) {
                Layer.close(loadIndex);
            }

            let res;
            try {
                res = JSON.parse(xhr.responseText || '{"code":0,"msg":"上传失败"}');
            } catch (e) {
                res = {code: 0, msg: '上传响应格式错误'};
            }

            if (res.code === 1) {
                showMsg(res.msg || '上传成功', 'success');
                const uploadModal = document.getElementById('uploadModal');
                if (window.$ && $.fn.modal) {
                    $(uploadModal).modal('hide');
                } else {
                    uploadModal.style.display = 'none';
                }
                setTimeout(() => window.location.reload(), 1000);
            } else {
                showMsg(res.msg || '上传失败', 'error');
            }
        };

        xhr.onerror = function() {
            submitBtn.disabled = false;
            submitBtn.textContent = '确认上传';
            if (loadIndex !== null && window.Layer) {
                Layer.close(loadIndex);
            }
            showMsg('网络错误，上传失败，请重试', 'error');
        };

        xhr.send(formData);
    });

    // 模态框关闭后重置表单
    const uploadModal = document.getElementById('uploadModal');
    if (uploadModal) {
        uploadModal.addEventListener('hidden.bs.modal', function() {
            uploadForm.reset();
            const submitBtn = uploadForm.querySelector('button[type="submit"]');
            if (submitBtn) {
                submitBtn.disabled = false;
                submitBtn.textContent = '确认上传';
            }
            document.getElementById('currentItemName').textContent = '未选择项目';
        });
    }

    console.log("原生JS初始化完成，文件上传格式校验已启用");
});

// 兜底保障
if (typeof window.setUploadItem === 'undefined') {
    window.setUploadItem = setUploadItem;
    console.log("兜底：setUploadItem已挂载到window对象");
}
</script>
{/block}
